/*
 * Copyright (C) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cmsis_os2.h>
#include <unistd.h> 
#include "lwip/sockets.h"
#include "aht20.h"
#include "HiSpark_WiFi_IoT_EM_VER.h"

extern int new_fd,sock_fd,is_accepted;
extern osMutexId_t g_mutexId;
int beep_status;
char recvbuf[512];

/**************************************************
 * 任务：deal_command_task
 * 命令处理任务
 * ***********************************************/
int deal_command_task(void)
{
    osMutexAcquire(g_mutexId, osWaitForever);
    ssize_t ret;
    //客户端地址信息
    struct sockaddr_in client_sock;
    int sin_size;
    while (1)
    {
        printf("start accept\n");

        //调用accept函数从队列中
        sin_size = sizeof(struct sockaddr_in);

        if ((new_fd = accept(sock_fd, (struct sockaddr *)&client_sock, (socklen_t *)&sin_size)) == -1)
        {
            perror("accept");
        }
        printf("accept succeed\n");
        is_accepted = 1;
        while (1)
        {
            bzero(recvbuf, sizeof(recvbuf));
            //接收数据,并根据命令对相应的设备执行控制命令
            if (recv(new_fd, recvbuf, sizeof(recvbuf), 0) < 0)
            {
                printf("recv error\n");
                close(new_fd);
                is_accepted = 0;
                break;
            }
            else
            {
                //处理数据
                if (NULL != strstr(recvbuf, "Beep"))
                {
                    //开启蜂鸣器
                    if (NULL != strstr(recvbuf, "ON"))
                    {
                        BeepStatusSet(ON);
                        beep_status = 1;
                        printf("Beep On!\n");
                    }
                    //关闭蜂鸣器
                    else if (NULL != strstr(recvbuf, "OFF"))
                    {
                        BeepStatusSet(OFF);
                        beep_status = 0;
                        printf("Beep Off!\n");
                    }
                }
            }
        }
    }
    osMutexRelease(g_mutexId);
}